package com.bytedance.touch.view

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import com.bytedance.touch.message.ChannelManager
import com.bytedance.touch.R
import com.bytedance.touch.message.MsgHelper
import com.korion.channel.ChannelListener
import com.korion.channel.IChannel
import java.lang.ref.WeakReference

class ControlView(context: Context, attrs: AttributeSet?, defaultStyle: Int):
    FrameLayout(context, attrs, defaultStyle), View.OnClickListener , ChannelListener {

    constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)

    constructor(context: Context): this(context, null)

    companion object {
        private const val TAG = "ControlView"
    }

    private val btn0: Button
    private val edt_ip: EditText
    private val tv_tip: TextView
    private var mMsgHelper: MsgHelper? = null

    //TODO: 设置host、port
    private var mHost: String = ""
    private val mPort = 8000

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.control_view_layout, this, true)
        btn0 = view.findViewById(R.id.btn0)
        edt_ip = view.findViewById(R.id.edt_ip)
        tv_tip = view.findViewById(R.id.tv_tip)
        btn0.setOnClickListener(this)
    }

    override fun onClick(view: View) {
        when(view.id){
            R.id.btn0 -> {
                if (mMsgHelper == null){
                    val ip = edt_ip.text.toString().trim()
                    mHost = ip
                    ChannelManager.INSTANCE.init(ip, mPort, WeakRefChannelListener(this))
                }
            }
        }
    }

    override fun onConnected(channel: IChannel, host: String, port: Int) {
        Log.d(TAG, "onConnected: $host:$port")
        mMsgHelper = MsgHelper(channel)
    }

    override fun onFailure(error: String?) {
        Log.d(TAG, "onFailure: error: $error")
    }

    override fun onMessage(bytes: ByteArray, size: Int) {

    }

}

class WeakRefChannelListener(listener: ChannelListener): ChannelListener {

    private val mRef = WeakReference(listener)

    override fun onConnected(channel: IChannel, host: String, port: Int) {
        mRef.get()?.onConnected(channel, host, port)
    }

    override fun onFailure(error: String?) {
        mRef.get()?.onFailure(error)
    }

    override fun onMessage(bytes: ByteArray, size: Int) {
        mRef.get()?.onMessage(bytes, size)
    }
}